package com.xinqi.modules.stats.score.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xinqi.common.core.enums.TotalScoreTypeEnum;
import com.xinqi.common.core.utils.MessageUtils;
import com.xinqi.common.base.error.CommonErrors;
import com.xinqi.common.mybatis.data.service.impl.BaseServiceImpl;
import com.xinqi.common.mybatis.utils.Queries;
import com.xinqi.modules.course.clazz.client.ClassClient;
import com.xinqi.modules.course.clazz.dto.rsp.ClassResultDTO;
import com.xinqi.modules.stats.score.convert.CourseTotalScoreConfigConvert;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreBaseConfigEntity;
import com.xinqi.modules.stats.score.domain.CourseTotalScoreConfigEntity;
import com.xinqi.modules.stats.score.dto.req.*;
import com.xinqi.modules.stats.score.dto.rsp.CourseTotalScoreConfigResultDTO;
import com.xinqi.modules.stats.score.mapper.CourseTotalScoreBaseConfigMapper;
import com.xinqi.modules.stats.score.mapper.CourseTotalScoreConfigMapper;
import com.xinqi.modules.stats.score.service.CourseTotalScoreConfigService;
import com.xinqi.modules.stats.score.service.CourseTotalScoreTypeConfigService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 总成绩等级制分值配置表服务层实现
 *
 * @author: system
 * @date: 2023/03/26
 */
@Service("courseTotalScoreConfigService")
@RequiredArgsConstructor
public class CourseTotalScoreConfigServiceImpl extends BaseServiceImpl<CourseTotalScoreConfigMapper, CourseTotalScoreConfigEntity> implements CourseTotalScoreConfigService {

    private final CourseTotalScoreConfigConvert courseTotalScoreConfigConvert;

    private final CourseTotalScoreBaseConfigMapper courseTotalScoreBaseConfigMapper;

    private final ClassClient classClient;

    private final CourseTotalScoreTypeConfigService courseTotalScoreTypeConfigService;

    /**
     * 初始化课程栏目等级分制配置
     */
    @Override
    public List<CourseTotalScoreConfigResultDTO> initCourseTotalScoreConfig(CourseTotalScoreConfigClassDTO dto) {
        if (TotalScoreTypeEnum.ALL_SCORE.getCode().equals(dto.getType())) {
            ClassResultDTO classResultDTO = classClient.findClass(dto.getClassId()).getData();
            dto.setCourseId(classResultDTO.getCourseId());
            // 先删除
            CourseTotalScoreConfigClassDTO classDTO = new CourseTotalScoreConfigClassDTO();
            classDTO.setClassId(dto.getClassId());
            this.baseMapper.deleteCourseTypeConfig(classDTO);
            // 后初始化
            LambdaQueryWrapper<CourseTotalScoreBaseConfigEntity> wrapper = Queries.lambda();
            wrapper.orderByAsc(CourseTotalScoreBaseConfigEntity::getSort);
            List<CourseTotalScoreBaseConfigEntity> baseConfigEntities = courseTotalScoreBaseConfigMapper.selectList(wrapper);
            List<CourseTotalScoreConfigEntity> configEntities = baseConfigEntities.stream().map(v -> {
                CourseTotalScoreConfigEntity configEntity = courseTotalScoreConfigConvert.convert(v);
                configEntity.setId(null);
                configEntity.setCourseId(classResultDTO.getCourseId());
                configEntity.setClassId(dto.getClassId());
                return configEntity;
            }).collect(Collectors.toList());
            if (this.saveBatch(configEntities)) {
                return this.findCourseTotalScoreConfig(dto);
            } else {
                return null;
            }
        } else {
            CourseTotalScoreConfigInitDTO initDTO = new CourseTotalScoreConfigInitDTO();
            initDTO.setClassId(dto.getClassId());
            initDTO.setType(dto.getType());
            return courseTotalScoreTypeConfigService.initCourseTotalScoreTypeConfig(initDTO);
        }
    }

    /**
     * 查询课程栏目等级分制
     */
    @Override
    public List<CourseTotalScoreConfigResultDTO> findCourseTotalScoreConfig(CourseTotalScoreConfigClassDTO dto) {
        if (TotalScoreTypeEnum.ALL_SCORE.getCode().equals(dto.getType())) {
            LambdaQueryWrapper<CourseTotalScoreConfigEntity> wrapper = Queries.lambda();
            wrapper.eq(CourseTotalScoreConfigEntity::getClassId, dto.getClassId());
            wrapper.orderByAsc(CourseTotalScoreConfigEntity::getSort);
            List<CourseTotalScoreConfigResultDTO> list = this.baseMapper.selectDtoList(wrapper, courseTotalScoreConfigConvert::convert);
            if (list == null || list.size() == 0) {
                this.initCourseTotalScoreConfig(dto);
                list = this.baseMapper.selectDtoList(wrapper, courseTotalScoreConfigConvert::convert);
            }
            return list;
        } else {
            return courseTotalScoreTypeConfigService.courseTotalScoreTypeConfig(dto);
        }
    }

    /**
     * 设置课程栏目等级分制
     */
    @Override
    public List<CourseTotalScoreConfigResultDTO> setCourseTotalScoreConfig(CourseTotalScoreConfigSetDTO dto) {

        CommonErrors.BAD_REQUEST.check(Objects.nonNull(dto.getType()), MessageUtils.message("course.content.total.score.type.valid"));
        CommonErrors.BAD_REQUEST.check(dto.getList() != null && dto.getList().size() < 7, MessageUtils.message("course.content.total.score.config.valid"));
        dto.getList().forEach(item -> {
            CommonErrors.BAD_REQUEST.check(item.getMax() <= 100, MessageUtils.message("等级分值上限不能超过100"));
        });
        if (TotalScoreTypeEnum.ALL_SCORE.getCode().equals(dto.getType())) {
            // 先删除
            CourseTotalScoreConfigClassDTO classDTO = new CourseTotalScoreConfigClassDTO();
            classDTO.setClassId(dto.getClassId());
            this.baseMapper.deleteCourseTypeConfig(classDTO);
            // 后添加
            ClassResultDTO classResultDTO = classClient.findClass(dto.getClassId()).getData();
            List<CourseTotalScoreConfigEntity> list = dto.getList().stream().map(v -> {
                CourseTotalScoreConfigEntity entity = new CourseTotalScoreConfigEntity();
                entity.setCourseId(classResultDTO.getCourseId());
                entity.setClassId(dto.getClassId());
                entity.setMax(v.getMax());
                entity.setMin(v.getMin());
                entity.setGrade(v.getGrade());
                entity.setSort(v.getSort());
                return entity;
            }).collect(Collectors.toList());
            if (this.saveBatch(list)) {
                return this.findCourseTotalScoreConfig(classDTO);
            } else {
                return null;
            }
        } else {
            if (courseTotalScoreTypeConfigService.setCourseTotalScoreTypeConfig(dto)) {
                CourseTotalScoreConfigClassDTO classDTO = new CourseTotalScoreConfigClassDTO();
                classDTO.setClassId(dto.getClassId());
                classDTO.setType(dto.getType());
                return courseTotalScoreTypeConfigService.courseTotalScoreTypeConfig(classDTO);
            } else {
                return null;
            }
        }
    }

    /**
     * 获取等级分值默认值
     */
    @Override
    public List<CourseTotalScoreBaseConfigEntity> getCourseScoreDefaultConfig() {
        LambdaQueryWrapper<CourseTotalScoreBaseConfigEntity> wrapper = Queries.lambda();
        wrapper.orderByAsc(CourseTotalScoreBaseConfigEntity::getSort);
        return courseTotalScoreBaseConfigMapper.selectList(wrapper);
    }

    /**
     * 判断等级设置是否合理
     */
    private boolean checkLevelNum(List<CourseTotalScoreConfigDTO> list) {
        for (int i = 0; i < list.size(); i++) {
            if (i > 0) {
                if (list.get(i - 1).getMin() < list.get(i).getMax()) {
                    return false;
                }
            }
            if (i == list.size() - 1) {
                if (list.get(i).getMin() != 0) {
                    return false;
                }
            }
        }
        return true;
    }

}
